using System;
using UnityEngine;

namespace Yoozoo.Core.Common
{
    [RequireComponent(typeof(ParticleSystem))]
    public class ParticleCountGrading : MonoBehaviour
    {
        public ParticleSystem particleSystem;
        [Header("限制最大粒子数量，如果勾选走以下参数，不勾选会走全局参数比例")]
        public bool custom = false;

        [Header("品质为Perfect时启用")]
        public int level0;
        [Header("品质为High、Middle时启用")]
        public int level1;
        [Header("品质为Low、VeryLow时启用")]
        public int level2;

        public void ChangeLevel(int lv,float factor)
        {
            if (!particleSystem) return;
            var particleSystemMain = particleSystem.main;
            
            if (!custom)
            {
                // 如果不是自定义，根据全局因子来控制
                int c = particleSystemMain.maxParticles;
                level0 = (int)(c * factor);
                level1 = (int)(c * factor);
                level2 = (int)(c * factor);
            }

            switch (lv)
            {
                case 0:
                    particleSystemMain.maxParticles = level0;
                    break;
                case 1:
                    particleSystemMain.maxParticles = level1;
                    break;
                case 2:
                    particleSystemMain.maxParticles = level2;
                    break;
                default:
                    particleSystemMain.maxParticles = level2;
                    break;
            }
            
        }
        
        private void Awake()
        {
            if (QualityHelper.ParticleQualityListener!=null)
            {
                QualityHelper.ParticleQualityListener.AddParticleCountGrading(this);
            }
        }

        private void OnDestroy()
        {
            if (QualityHelper.ParticleQualityListener!=null)
            {
                QualityHelper.ParticleQualityListener.RemoveParticleCountGrading(this);
            }
        }


#if UNITY_EDITOR
        private void OnValidate()
        {
            ParticleSystem ps = GetComponent<ParticleSystem>();
            if (!particleSystem || ps!=particleSystem)
            {
                particleSystem = ps;
            }
        }
#endif
        
    }
}